using System;
using System.Collections.Generic;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 记忆节点数据结构
    /// 表示智能体记忆系统中的一个记忆单元
    /// </summary>
    [System.Serializable]
    public class MemoryNode
    {
        [Header("基础记忆信息")]
        public string nodeId;               // 唯一节点ID
        public MemoryType type;             // 记忆类型
        public string content;              // 记忆内容
        public string description;          // 详细描述
        
        [Header("语义信息")]
        public float[] embedding;           // 语义嵌入向量
        public List<string> keywords;       // 关键词
        public string subject;              // 主语
        public string predicate;            // 谓语
        public string objectEntity;         // 宾语
        
        [Header("时空信息")]
        public DateTime createdTime;        // 创建时间
        public DateTime lastAccessTime;     // 最后访问时间
        public Vector3 location;            // 相关位置
        public string locationName;         // 位置名称
        
        [Header("重要性和访问统计")]
        public int poignancy;              // 重要性分数(1-10)
        public int accessCount;            // 访问次数
        public float decayFactor;          // 衰减因子
        
        [Header("关联信息")]
        public List<string> relatedNodeIds; // 相关记忆节点ID
        public List<string> participants;   // 参与者
        public string sourceEventId;        // 源事件ID
        
        [Header("额外元数据")]
        public Dictionary<string, object> metadata; // 额外元数据
        public bool isExpired;             // 是否已过期
        public DateTime expirationTime;    // 过期时间
        
        public MemoryNode()
        {
            nodeId = System.Guid.NewGuid().ToString();
            createdTime = DateTime.Now;
            lastAccessTime = DateTime.Now;
            keywords = new List<string>();
            relatedNodeIds = new List<string>();
            participants = new List<string>();
            metadata = new Dictionary<string, object>();
            accessCount = 0;
            decayFactor = 0.99f;
            isExpired = false;
        }
        
        /// <summary>
        /// 从AgentEvent创建MemoryNode
        /// </summary>
        public static MemoryNode FromEvent(AgentEvent agentEvent)
        {
            var memoryNode = new MemoryNode
            {
                type = MemoryType.Event,
                content = agentEvent.description,
                description = agentEvent.description,
                embedding = agentEvent.embedding,
                keywords = new List<string>(agentEvent.keywords),
                subject = agentEvent.subject,
                predicate = agentEvent.predicate,
                objectEntity = agentEvent.objectEntity,
                createdTime = agentEvent.timestamp,
                lastAccessTime = agentEvent.timestamp,
                location = agentEvent.location,
                locationName = agentEvent.locationName,
                poignancy = agentEvent.poignancy,
                participants = new List<string>(agentEvent.participants),
                sourceEventId = agentEvent.eventId
            };
            
            // 设置过期时间（基于重要性）
            var daysToExpire = memoryNode.poignancy >= 7 ? 30 : 7; // 高重要性记忆保留更久
            memoryNode.expirationTime = memoryNode.createdTime.AddDays(daysToExpire);
            
            return memoryNode;
        }
        
        /// <summary>
        /// 创建思想记忆
        /// </summary>
        public static MemoryNode CreateThought(string content, int importance, Vector3 location, string locationName = "")
        {
            var thoughtNode = new MemoryNode
            {
                type = MemoryType.Thought,
                content = content,
                description = $"Thought: {content}",
                poignancy = importance,
                location = location,
                locationName = locationName
            };
            
            // 从内容提取关键词
            thoughtNode.ExtractKeywords();
            return thoughtNode;
        }
        
        /// <summary>
        /// 创建计划记忆
        /// </summary>
        public static MemoryNode CreatePlan(string planContent, DateTime scheduledTime, Vector3 targetLocation, string locationName = "")
        {
            var planNode = new MemoryNode
            {
                type = MemoryType.Plan,
                content = planContent,
                description = $"Plan: {planContent}",
                location = targetLocation,
                locationName = locationName,
                poignancy = 5 // 计划默认中等重要性
            };
            
            planNode.metadata["scheduledTime"] = scheduledTime;
            planNode.ExtractKeywords();
            return planNode;
        }
        
        /// <summary>
        /// 访问记忆节点（更新访问统计）
        /// </summary>
        public void Access()
        {
            lastAccessTime = DateTime.Now;
            accessCount++;
        }
        
        /// <summary>
        /// 计算记忆的新近度分数
        /// </summary>
        public float GetRecencyScore()
        {
            var timeDiff = (DateTime.Now - lastAccessTime).TotalHours;
            return Mathf.Exp(-(float)timeDiff * 0.01f); // 指数衰减
        }
        
        /// <summary>
        /// 计算记忆的重要性分数
        /// </summary>
        public float GetImportanceScore()
        {
            return poignancy / 10f; // 归一化到0-1
        }
        
        /// <summary>
        /// 检查记忆是否过期
        /// </summary>
        public bool CheckExpired()
        {
            if (!isExpired && DateTime.Now > expirationTime)
            {
                isExpired = true;
            }
            return isExpired;
        }
        
        /// <summary>
        /// 从内容提取关键词（简单实现）
        /// </summary>
        private void ExtractKeywords()
        {
            if (string.IsNullOrEmpty(content)) return;
            
            // 简单的关键词提取，实际应用中可以使用更复杂的NLP技术
            var words = content.ToLower().Split(new char[] { ' ', '.', ',', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
            var stopWords = new HashSet<string> { "the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by", "is", "was", "are", "were", "be", "been", "have", "has", "had", "do", "does", "did", "will", "would", "could", "should" };
            
            foreach (var word in words)
            {
                if (word.Length > 2 && !stopWords.Contains(word) && !keywords.Contains(word))
                {
                    keywords.Add(word);
                }
            }
        }
        
        /// <summary>
        /// 添加关联记忆
        /// </summary>
        public void AddRelatedMemory(string nodeId)
        {
            if (!relatedNodeIds.Contains(nodeId))
            {
                relatedNodeIds.Add(nodeId);
            }
        }
        
        /// <summary>
        /// 获取记忆的综合重要性（考虑访问频率）
        /// </summary>
        public float GetCompositeImportance()
        {
            var baseImportance = GetImportanceScore();
            var accessBonus = Mathf.Log(accessCount + 1) * 0.1f; // 访问频率加成
            return Mathf.Clamp01(baseImportance + accessBonus);
        }
    }
    
    /// <summary>
    /// 记忆类型枚举
    /// </summary>
    public enum MemoryType
    {
        Event,          // 事件记忆
        Thought,        // 思想记忆
        Chat,           // 对话记忆
        Observation,    // 观察记忆
        Plan,           // 计划记忆
        Reflection,     // 反思记忆
        Knowledge,      // 知识记忆
        Emotion         // 情感记忆
    }
}